package com.example.backend.controller;

import com.example.backend.dto.LoginResponseDTO;
import com.example.backend.entity.User;
import com.example.backend.mapper.UserMapper;
import com.example.backend.util.JwtUtil;
import com.example.backend.util.Result;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    private final UserMapper userMapper;
    private final BCryptPasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;
    public UserController(UserMapper userMapper, BCryptPasswordEncoder passwordEncoder, JwtUtil jwtUtil) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
        this.jwtUtil = jwtUtil;
    }

    // 注册
    @PostMapping("/register")
    public Result<Object> insert_user_register(@RequestBody Map<String, Object> registerData) {
        try {
            Boolean is_exist = userMapper.select_user_urn((String) registerData.get("username"));
            if (is_exist) {
                return Result.error("400", "username already exists");
            }
            // 判断是否管理员，管理员要核验秘钥
            if ((Integer)registerData.get("permission") == 1) {
                Boolean is_key_valid = userMapper.select_key((String)registerData.get("key"));
                if (!is_key_valid) {
                    return Result.error("400", "key is invalid");
                }
                userMapper.delete_key((String)registerData.get("key"));
                userMapper.insert_user_register(
                        (String)registerData.get("username"),
                        passwordEncoder.encode((String)registerData.get("password")),
                        1);
            }
            // 非管理员可以直接注册
            else {
                userMapper.insert_user_register(
                        (String)registerData.get("username"),
                        passwordEncoder.encode((String)registerData.get("password")),
                        0
                );
            }
            return Result.success();

        }
        catch (Exception e) {
            return Result.error("500", e.getMessage());
        }
    }

    // 登录验证
    @PostMapping("/login")
    public Result<LoginResponseDTO> select_user_login(@RequestBody Map<String, Object> loginData) {
        try {
            User user_db = userMapper.select_user_login((String) loginData.get("username"));
            if (user_db == null || !passwordEncoder.matches((String) loginData.get("password"), user_db.getPassword())) {
                return Result.error("400", "username or password is incorrect");
            }
            String token = jwtUtil.generateToken(user_db.getUsername(), user_db.getPermission());   // jwt
            LoginResponseDTO response = new LoginResponseDTO(user_db, token);
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("500", e.getMessage());
        }
    }
}

